package com.sea.human.controller;

import com.codecrane.core.Constants;
import com.codecrane.core.power.entity.PowerGroup;
import com.codecrane.core.power.entity.PowerUser;
import com.codecrane.core.power.service.PowerGroupService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.util.PerformanceStatusEnum;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.human.entity.Performance;
import com.sea.human.entity.PerformanceDetail;
import com.sea.human.service.PerformanceDetailService;
import com.sea.human.service.PerformanceService;
import com.sea.human.service.PerformanceTaskService;
import com.sea.physical.entity.CreateDespatchFreight;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;


/**
 *  控制器
 * @author 陈鸿飞
 *  <br/>
 *  <br/>
 */
@Controller
@RequestMapping("/sea/human/performanceDetail")
public class PerformanceDetailController {

    @Autowired
    private PerformanceDetailService performanceDetailService;
    @Autowired
    private PowerGroupService powerGroupService;
    @Autowired
    private PerformanceTaskService performanceTaskService;
    @Autowired
    private PerformanceService performanceService;


    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/addKPI")
    public String addKPI(Model model,@RequestParam("performanceId")Integer performanceId) {
        model.addAttribute("performanceId",performanceId);
        model.addAttribute("powerGroup",powerGroupService.findByPid(3L));
        model.addAttribute("task",performanceTaskService.findByCnd(null));

        return "/sea/human/performance/addKPI";
    }
    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/addOKR")
    public String addOKR(Model model,@RequestParam("performanceId")Integer performanceId) {
        model.addAttribute("performanceId",performanceId);
        model.addAttribute("powerGroup",powerGroupService.findByPid(3L));
        return "/sea/human/performance/addOKR";
    }

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/editKPI")
    public String editKPI(Model model,@RequestParam("id")Integer id) {
        PerformanceDetail performanceDetail = performanceDetailService.findById(id);
        model.addAttribute("performanceDetail",performanceDetail);
        model.addAttribute("powerGroup",powerGroupService.findByPid(3L));
        return "/sea/human/performance/editKPI";
    }
    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/editOKR")
    public String editOKR(Model model,@RequestParam("id")Integer id) {
        PerformanceDetail performanceDetail = performanceDetailService.findById(id);
        model.addAttribute("performanceDetail",performanceDetail);
        model.addAttribute("powerGroup",powerGroupService.findByPid(3L));
        return "/sea/human/performance/editOKR";
    }
    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/editCulture")
    public String editCulture(Model model,@RequestParam("id")Integer id) {
        PerformanceDetail performanceDetail = performanceDetailService.findById(id);
        model.addAttribute("performanceDetail",performanceDetail);
        model.addAttribute("powerGroup",powerGroupService.findByPid(3L));
        return "/sea/human/performance/editCulture";
    }


    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findOKRByPerformanceId")
    public AjaxTableReturn findOKRByPerformanceId(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     PerformanceDetail performanceDetail) {
        performanceDetail.setFlag(1);
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<PerformanceDetail> performanceList = performanceDetailService.findByCnd(performanceDetail);
        PageInfo<PerformanceDetail> page = new PageInfo<>(performanceList);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findKPIByPerformanceId")
    public AjaxTableReturn findKPIByPerformanceId(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     PerformanceDetail performanceDetail) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<PerformanceDetail> performanceList = performanceDetailService.findByCnd(performanceDetail);
        PageInfo<PerformanceDetail> page = new PageInfo<>(performanceList);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }
    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findCultureByPerformanceId")
    public AjaxTableReturn findCultureByPerformanceId(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                                  @RequestParam(value = "offset", defaultValue = "0") int start,
                                                  PerformanceDetail performanceDetail) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<PerformanceDetail> performanceList = performanceDetailService.findByCnd(performanceDetail);
        PageInfo<PerformanceDetail> page = new PageInfo<>(performanceList);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    /**
     * 保存
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(PerformanceDetail performanceDetail) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{

            if (null !=performanceDetail && performanceDetailService.save(performanceDetail)>0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 保存
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(PerformanceDetail performanceDetail) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{

            if (null !=performanceDetail && performanceDetailService.usave(performanceDetail)>0) {
                performanceService.updateScore(performanceDetail.getPerformanceId());
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }
    /**
     * 保存
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxReturn delete(Integer id) {
        AjaxReturn result = Ajax.fail().setMsg("删除失败！");
        try{
            if (null !=id && performanceDetailService.delete(id)>0) {
                result.setOk(true).setMsg("删除成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }


    /**
     * 导出收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, PerformanceDetail performanceDetail) {
        List<PerformanceDetail> list = performanceDetailService.export(performanceDetail);
        String[] title = {"部门","姓名","日期", "绩效目标","目标值","指标计算公式","权重", "考核办法","数据来源","类型","自评分","自评原因","上级评分","评级","状态"};
        String fileName = "绩效表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "绩效表";
        String[][] content = new String[list.size()][15];
        String name="";
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            PerformanceDetail obj = list.get(i);
            content[i][0] = obj.getGroupName();

            content[i][1] = obj.getUserName();
            name=obj.getUserName();
            content[i][2] = obj.getPerformanceDate();
            content[i][3] = obj.getPerformanceTask();
            content[i][4] = obj.getPerformanceTarget();
            content[i][5] = obj.getPerformanceDefine();
            content[i][6] = (null==obj.getPerformanceWeight()?0:obj.getPerformanceWeight())+"";
            content[i][7] = obj.getPerformanceCheck();
            content[i][8] = obj.getPerformanceSource();
            Integer flag = obj.getFlag();
            if(flag==0){
                content[i][9] = "KPI";
            }else if(flag==1){
                content[i][9] = "OKR";
            }else{
                content[i][9] = "企业文化";
            }
            content[i][10] = obj.getPerformanceSelfGrade().toString();
            content[i][11] = (null==obj.getPerformanceSelfGradeReason()?"":obj.getPerformanceSelfGradeReason());
            content[i][12] = (null==obj.getPerformanceGrade()?0:obj.getPerformanceGrade())+"";

            //判断是否是第一条
            if(i==0){
                content[i][13]=obj.getPerformanceLevel();
                content[i][14]= PerformanceStatusEnum.getStatus(obj.getPerformanceStatus());
            }else{
                String name2=content[i-1][1];
                if(!name.equals(name2)){
                    content[i][13]=obj.getPerformanceLevel();
                    content[i][14]= PerformanceStatusEnum.getStatus(obj.getPerformanceStatus());
                }else{
                    content[i][13]="";
                    content[i][14]= "";
                }
            }
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
